// cSpell:words Captcha
import Chance = require("chance")
import koa = require("koa")
import * as sc from "svg-captcha"
import { aGetString, aSetString, aUnset } from "../cache/Cache"

sc.options.width = 100
sc.options.height = 40

const chance = new Chance()

export async function aGenerate(ctx: koa.Context) {
    const captcha = sc.create({ size: 4, ignoreChars: "0o1i", noise: 4,
        color: true, background: "#fff"})
    const text = captcha.text

    const id = chance.hash()
    ctx.cookies.set("captcha_id", id, { signed: true, httpOnly: true })
    await aSetString(["captcha", id], text)

    ctx.set("X-Captcha-Id", id)
    ctx.body = captcha.data
    ctx.type = "image/svg+xml"
}

export async function aCheck(id: string, text: string) {
    if (!(id && text)) return false
    const expected = await aGetString(["captcha", id])
    return expected && text && expected.toLowerCase() === text.toLowerCase()
}

export async function aClearById(id: string) {
    await aUnset(["captcha"], [id])
}

